<?php
namespace member\service;

use herosphp\core\Loader;
use herosphp\bean\Beans;

Loader::import('admin.service.interfaces.IManagerService');

/**
 * admin(Service)接口实现
 * @package admin\service
 * @author yangjian<yangjian102621@gmail.com>
 */
class MemberGroupService extends CommonService {
    /**
     * @return array|mixed
     */
    public function getGroupList()
    {
        $conditions['status'] = 1;
        $conditions['app_id'] = appId();
        $fields = "id,name";
        return $this ->getItems($conditions,$fields);
    }

    public function getGroupItems($conditions, $fields, $order, $limit, $group, $having)
    {
        $items =  parent::getItems($conditions, $fields, $order, $limit, $group, $having); // TODO: Change the autogenerated stub
        $memberService  = Beans::get('member.member.service');
        $managerService = Beans::get('admin.adminManager.service');
        $member = $memberService -> getCount();//分组计算每个分类有多少人
        $temp = array();
        $managerIds=array(0);
        foreach ($items as $value){
            $value['total'] = 0;
            foreach ($member as $v){
                if( $value['id']==$v['group_id'] ){
                    $value['total'] = $v['total'];
                }
            }
            $temp[] = $value;
            $managerIds[] = $value['manager_id'];
        }
        $items = $temp;

        $managerConditions['id']['$in'] = $managerIds;
        $manager = $managerService -> getItems($managerConditions, 'id,username', "", "", "", "");
        $temp = array();
        foreach ($items as $value){
            foreach ($manager as $vv){
                if( $value['manager_id'] == $vv['id'] ){
                    $value['manager_name'] = $vv['username'];
                }
            }
            $temp[] = $value;
        }

        /*
        $sql = "select `name`,`addtime`,`status`,manager.username as `manager_name`,count(member.id) as `total` 
                from member,memberGroup,admin_manager as manager 
                where member.app_id = ".appId()." and  member.group_id = member_group.id
                and member_group.manager_id = manager.id group by member.group_id";
        */
        //echo $sql;die;
        return $items=$temp;
    }

    /**
     * 判断分组是否为空，空返回true，非空返回false
     * @param $id
     * @return bool
     */
    public function isEmptyGroup( $id ){
        $memberService  = Beans::get('member.member.service');
        $member = $memberService -> getCount( $id );
        if( $member[0]['total'] ){
            return false;
        }else{
            return true;
        }
    }
}
